package collectors.wrapper;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ArrayNode;
import org.joda.time.DateTime;

import collectors.file.models.FileInfo;

/*import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; */

import play.Logger;
import play.Play;
import play.libs.F.Promise;
import play.libs.Json;
import play.libs.WS;

public class FilyouWrapper {

	private static FilyouWrapper instance = null;

	private FilyouWrapper(){}

	public static FilyouWrapper getInstance(){
		if(instance == null){
			instance = new FilyouWrapper();
		}
		return instance;
	}

	public static List<FileInfo> search(Long id, String query) {
		
		String filyou = Play.application().configuration().getString("sm.filyou.search");
		
		filyou = filyou.replaceAll("USER_ID", id + "");
		Logger.debug(filyou);

		Promise<WS.Response> result = WS.url(filyou).setQueryParameter("q", query).get();

		ArrayList<FileInfo> fileList;
		
		JsonNode node = result.get().asJson();
		fileList = new ArrayList<FileInfo>(node.size());
		
		FileInfo fileInfo;
		
		if (node.size() > 0) { 
		   for (int i=0; i<node.size(); i++){ 
			   fileInfo = new FileInfo();
			   fileInfo.name = node.get(i).findPath("name").getTextValue();
			   fileInfo.size = node.get(i).findPath("size").getTextValue();
			   fileInfo.isDir = node.get(i).findPath("dir").getBooleanValue();
			   fileInfo.path = node.get(i).findPath("path").getTextValue();
			   fileInfo.modifiedDate = new Date(node.get(i).findPath("path").getLongValue());
			   fileList.add(fileInfo);
		   } 
		}  
		
		return fileList;
	}
	

	public InputStream download(Long id, String path) {
		String filyou = Play.application().configuration().getString("sm.filyou.download");
		
		filyou = filyou.replaceAll("USER_ID", id + "");
		Logger.debug(filyou);
		
		Promise<WS.Response> result = WS.url(filyou).setQueryParameter("path", path).get();
		
		return result.get().getBodyAsStream();
	}
	
	public static String searchOld(Long id, String query) {
		String filyou = Play.application().configuration().getString("sm.filyou.search");
		
		filyou = filyou.replaceAll("USER_ID", id + "");
		Logger.debug(filyou);

		Promise<WS.Response> result = WS.url(filyou).setQueryParameter("q", query).get();

		return result.get().getBody();
	}
	
}
